﻿if (typeof Axis == "undefined") Axis = {};
if (typeof Axis.Admin == "undefined") Axis.Admin = {};
var checkListAuthorized;
Axis.Admin.User = {
    Init: function () {
        var thisObj = this;
        thisObj.Grid.Init();
        var cmaskdate = new CMaskDate();
        cmaskdate.Init($("input[role=datepicker]"));
        var cdropdown = new CDropDownCheckList({ width: 200 });
        cdropdown.Init("#ddlFilter");

        $("#ddlCategory option").each(function () {
            var text = $.RemoveHTMLTags($(this).text());
            $(this).text(text);
        });
        checkListAuthorized = new CDropDownCheckList({ width: 302, maxDropHeight: 110, firstItemChecksAll: true });
        checkListAuthorized.Init("#ddlCategory, [id$='ddlProvinceFilter'],[id$='ddlEducationFilter'],[id$='ddlClassFilter'],[id$='ddlMaritalStatusFilter'],[id$='ddlEducationFilter'],[id$='ddlJobFilter'],[id$='ddlTypeFilter'],[id$='ddlGenderFilter']");
        $("#FormFilter").hide();
        $("#FormEdit").hide();
        thisObj.Click();
    },

    Grid: {
        ID: "#GridContents",
        PagesID: "#GridPages",
        GridURL: "Service/UserService.ashx?Action=GET&Context=GroupUser",
        Instance: null,
        Init: function () {
            var thisObj = this;
            var options = {
                url: thisObj.GridURL,
                datatype: "json",
                colNames: [
                    'ID', 'FullName', 'Login Name', 'Email', 'Type', 'CategoriesIDs', 'Action'
                ],
                colModel: [
                    { name: 'ID', index: 'ID', width: 50, hidden: true, frozen: true },
                    { name: 'FullName', index: 'FullName', width: 200, frozen: true },
                    { name: 'LoginName', index: 'LoginName', width: 100 },
                    { name: 'Email', index: 'Email', width: 170, align: 'center', hidden: true },
                    { name: 'Type', index: 'Type', width: 50, hidden: true },
                    { name: 'CategoriesIDs', index: 'CategoriesIDs', width: 70, align: 'center', hidden: true },
                    { name: 'Action', index: 'Action', width: 55, align: 'center' }
                ],
                afterInsertRow: function (rowid, aData, addData) {

                    var action = $.string.Format("<img class='imgAction' src='../../Images/16x16/authorized.png' onclick=\"ShowAuthorized('{0}')\" title='Phân quyền'/><img class='imgAction' src='../../Images/16x16/edit.png' onclick=\"ShowEdit('{0}')\" title='Sửa'/><img class='imgAction' src='../../Images/16x16/cancel.png' onclick=\"ShowDelete('{0}')\" title='Xóa'/>", rowid);
                    $(thisObj.ID).jqGrid('setCell', rowid, 'Action', action);

                },
                onCellSelect: function (rowid, iCol, cellcontent, e) {
                },
                onSelectRow: function (rowid, status, e) {
                },
                ondblClickRow: function (rowid, iRow, iCol, e) {
                },
                height: 'auto',
                rownumbers: true,
                autowidth: true,
                shrinkToFit: false,
                rowNum: 10,
                pager: thisObj.PagesID
            };
            thisObj.Instance = new CGrid(options);
            thisObj.Instance.Init(thisObj.ID);
            thisObj.Instance.NavGrid();
            thisObj.Instance.FrozenColumns();
        },
        Reload: function () {
            var thisObj = this;
            if (thisObj.Instance)
                thisObj.Instance.ReloadGrid();
        },
        SelectRow: function () {
            var thisObj = this;
            if (thisObj.Instance) {
                return thisObj.Instance.SelectRow();
            }
            return null;
        }
    },
    DialogEdit: {
        ID: "#FormEdit",
        Dialog: null,
        Init: function (action, opts) {
            var thisObj = this;
            Axis.Admin.User.ClearForm();

            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Edit User",
                    width: 440,
                    height: 400
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
            var buttonText = "";
            switch (action) {
                case "INSERT":
                    thisObj.Dialog.SetTitle("Add New User");
                    $(thisObj.ID).find("[data-role='INSERT']").show();
                    $(thisObj.ID).find("#txtLoginName").focus();
                    buttonText = "Add";
                    $("#chk_ResetPassword").css("visibility", "hidden");
                    $("#txtPassword").removeAttr("readonly").removeAttr("no-data");
                    $("#txtLoginName,#txtPassword,#txtEmail,#txtUserFullName,#chk_SuperAdmin").parent().show();
                    $("#ddlCategory,#Admin_Menu").parent().hide();
                     $("#txtLoginName,#txtPassword").removeAttr("readonly", "readonly");
                    break;
                case "UPDATE":
                    thisObj.Dialog.SetTitle("Edit: " + opts.LoginName);
                    if (opts) {
                        $.each(opts, function (key, value) {
                            $(thisObj.ID).find("[data-field=" + key + "]").val(value);
                        });
                        if (opts.Type == "2") {
                            $("#chk_SuperAdmin").attr("checked", "checked");
                        }
                    }
                    buttonText = "Update";
                    $("#txtLoginName,#txtPassword").attr("readonly", "readonly");

                    $("#txtLoginName,#txtPassword").attr("readonly", "readonly");
                    $("#txtEmail,#txtUserFullName").removeAttr("readonly");
                    $("#txtLoginName,#txtPassword,#txtEmail,#txtUserFullName,#chk_SuperAdmin").parent().show();
                    $("#ddlCategory,#Admin_Menu").parent().hide();
                    thisObj.SetTitle("Cập nhật thông tin");
                    $("#chk_ResetPassword").css("visibility", "visible");
                    break;
                case "AUTHORIZED":
                    if (opts) {
                        $("#txtUserID").val(opts.ID);
                        var UserGroupIDs = opts.CategoriesIDs;
                        var arr = UserGroupIDs.split(",");
                        $.each(arr, function (index, value) {
                            var $option = $("#ddlCategory").find($.string.Format("option[value='{0}']", value));
                            $option.attr("selected", "selected");
                            $(".Menu_Tree_Items").find("input:checkbox[value='" + value + "']").attr("checked", "checked");
                        });

                        if (checkListAuthorized)
                            checkListAuthorized.Refresh();
                    }

                    $("#ddlCategory,#Admin_Menu").parent().show();
                    $("#txtLoginName,#txtPassword,#txtEmail,#txtUserFullName").attr("readonly", "readonly");
                    $("#txtLoginName,#txtPassword,#txtEmail,#txtUserFullName,#chk_SuperAdmin").parent().hide();
                    buttonText = "Update";
                    thisObj.SetTitle("Phân quyền");
                    break;
            }
            var buttons = [
                        {
                            text: buttonText,
                            click: function (e) {
                                Axis.Admin.User.Update(action, opts);

                            }
                        },
                        {
                            text: "Cancel",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

            ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        },
        SetTitle: function (title) {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.SetTitle(title);
            }
        }
    },
    DialogFilter: {
        ID: "#FormFilter",
        Dialog: null,
        Init: function (type, opts) {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Filter",
                    width: 330,
                    height: 400,
                    buttons: [
                        {
                            text: "Search",
                            click: function (e) {
                                var data = {};
                                $("#FormFilter").find("input,select").each(function () {
                                    var $this = $(this);
                                    if ($this.attr("data-field")) {
                                        var key = $this.attr("data-field");
                                        var value = $this.val();
                                        if ($.isArray(value)) {
                                            data[key] = value.join(", ");
                                        }
                                        else {
                                            data[key] = value;
                                        }
                                    }
                                });
                                data = decodeURIComponent($.param(data));
                                $("#GridContents").jqGrid('setGridParam', { url: "Service/UserService.ashx?Action=GET&" + data, page: 1 }).trigger("reloadGrid");
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Cancel",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

                    ]
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        }
    },
    ClearForm: function () {
        $("#FormEdit").find("[data-field]").each(function () {
            var $this = $(this);
            $this.val("");
            if ($this.is("select")) {
                var value = $this.find("option[Default-Value='1']").attr("value");
                $this.val(value);
            }

        });
        $("#chk_SuperAdmin").removeAttr("checked");
        $("#txtPassword").attr({
            "readonly": "readonly",
            "no-data": "1"
        });
        $("#chk_ResetPassword").removeAttr("checked");
        $("#FormEdit [data-role='INSERT']").hide();
        $("#ddlCategory option").removeAttr("selected");
        if (checkListAuthorized)
            checkListAuthorized.Refresh();
        $('.Menu_Tree').tree('uncheckAll');
    },
    Update: function (type, opts) {
        var thisObj = this;
        var data = {};
        switch (type) {
            case "INSERT":
                $("#FormEdit").find("input,select").each(function () {
                    var $this = $(this);
                    if ($this.attr("data-field")) {
                        var key = $this.attr("data-field");
                        data[key] = $this.val();
                    }
                });
                break;
            case "UPDATE":
                $("#FormEdit").find("input,select").each(function () {
                    var $this = $(this);
                    if ($this.attr("data-field") && $this.attr("data-role") != "INSERT" && $this.attr("no-data") != "1") {
                        var key = $this.attr("data-field");
                        data[key] = $this.val();
                    }
                });
                data.IsSupperUser = $("#chk_SuperAdmin").is(":checked") ? 1 : 0;
                break;
            case "AUTHORIZED":
                var UserGroupIDs = $("#ddlCategory").val();
                data.UserGroupIDs = "";
                if (UserGroupIDs && UserGroupIDs.length) {
                    data.UserGroupIDs = UserGroupIDs.join(",");
                }
                var admin_menu = "";

                $(".Menu_Tree_Items").find("input:checkbox").each(function (index) {

                    if ($(this).is(":checked")) {
                        if (admin_menu) {
                            admin_menu += ",";
                        }
                        admin_menu += $(this).val();
                    }


                });
                if (data.UserGroupIDs) {
                    admin_menu = "," + admin_menu;
                }
                data.UserGroupIDs = data.UserGroupIDs + admin_menu;
                data.ActionUserID = $("#txtUserID").val();
                break;
            case "DELETE":
                data.ID = opts.ID;
                break;
        }

        data.Action = type;
        $.Ajax({
            url: 'Service/UserService.ashx',
            type: 'POST',
            data: data,
            success: function (data, textStatus, jqXHR) {
                if (data) {
                    data = eval("(" + data + ")");
                    if (data.IsSuccessfull) {
                        thisObj.Grid.Reload();
                        thisObj.DialogEdit.Close();
                    }

                    $.CAlert.Alert({
                        Title: "Thông báo",
                        Content: data.Description,
                    });
                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    Click: function () {
        var thisObj = this;
        $("#imgUserAdd").click(function () {
            thisObj.DialogEdit.Init("INSERT");
        });
        $("#imgUserEdit").click(function () {
            var rowData = thisObj.Grid.SelectRow();
            if (rowData && rowData.ID)
                thisObj.DialogEdit.Init("UPDATE", rowData);
            else {
                $.CAlert.Alert({
                    Title: "Sửa tài khoản",
                    Content: "Vui lòng chọn tài khoản cần sửa.",
                });
            }
        });
        $("#imgUserDel").click(function () {
            var rowData = thisObj.Grid.SelectRow();
            if (rowData && rowData.ID) {
                $.CAlert.Confirm({
                    Title: "Xóa tài khoản",
                    Content: $.string.Format("Bạn có chắc muốn xóa tài khoản [{0}].", rowData.Email),
                }, function (isOK) {
                    if (isOK)
                        thisObj.Update("DELETE", rowData);
                });
            }
            else {
                $.CAlert.Alert({
                    Title: "Xóa tài khoản",
                    Content: "Vui lòng chọn tài khoản cần xóa.",
                });
            }

        });
        $("#imgUserFilter").click(function () {
            thisObj.DialogFilter.Init();
        });
        $("#chk_ResetPassword").change(function () {
            if ($(this).is(":checked")) {
                $("#txtPassword").removeAttr("readonly").removeAttr("no-data").focus();
            }
            else {
                $("#txtPassword").attr({
                    "readonly": "readonly",
                    "no-data": "1"
                });
            }
        });
    },
    Validate: function () {

    },
    GetAdminCategory: function () {
        var data = {
            Action: "GetAdminCategory",
            FunctionCode: "AdminCategory",
            Context: "GroupUser"
        };
        $.Ajax({
            url: 'Service/UserService.ashx',
            type: 'POST',
            data: data,
            success: function (data, textStatus, jqXHR) {
                if (data) {
                    data = eval("(" + data + ")");
                    var ret_parent = "";
                    $.each(data, function (index, item) {
                        if (item.ParentID == 0)
                            ret_parent += $.string.Format('<li menuid="{0}"><input type="checkbox" value="{0}" code="{1}" id="menu_{0}" /><label for="menu_{0}">{2}</label></li>', item.ID, item.Code, $.RemoveHTMLTags(item.Name));
                    });

                    $(".Menu_Tree_Items").html(ret_parent);
                    $.each(data, function (index, item) {
                        var ret_child = "";
                        if (item.ParentID != 0) {
                            ret_child += $.string.Format('<li menuid="{0}"><input type="checkbox" value="{0}" code="{1}" id="submenu_{0}" /><label for="submenu_{0}">{2}</label></li>', item.ID, item.Code, $.RemoveHTMLTags(item.Name));
                            var $parent = $(".Menu_Tree_Items li[menuid='" + item.ParentID + "']");
                            if ($parent.length) {
                                if ($parent.find("ul").length == 0) {
                                    $parent.append("<ul></ul>");
                                }
                                $(".Menu_Tree_Items li[menuid='" + item.ParentID + "'] ul").append(ret_child);
                            }
                        }

                    });
                    $('.Menu_Tree').tree();
                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    }
};
$(function () {
    Axis.Admin.User.Init();
    Axis.Admin.User.GetAdminCategory();


});
function ShowEdit(rowID) {
    var thisObj = Axis.Admin.User;
    var rowData = $(thisObj.Grid.ID).jqGrid('getRowData', rowID);
    if (rowData && rowData.ID)
        thisObj.DialogEdit.Init("UPDATE", rowData);
}
function ShowAuthorized(rowID) {
    var thisObj = Axis.Admin.User;
    var rowData = $(thisObj.Grid.ID).jqGrid('getRowData', rowID);
    if (rowData && rowData.ID)
        thisObj.DialogEdit.Init("AUTHORIZED", rowData);
}
function ShowDelete(rowID) {
    var thisObj = Axis.Admin.User;
    if (rowID) {
        var rowData = $(thisObj.Grid.ID).jqGrid('getRowData', rowID);
        $.CAlert.Confirm({
            Title: "Xóa tài khoản",
            Content: $.string.Format("Bạn có chắc muốn xóa tài khoản: [{0}].", rowData.LoginName)
        }, function (isOK) {
            if (isOK)
                thisObj.Update("DELETE", { ID: rowID });
        });
    }
    else {
        $.CAlert.Alert({
            Title: "Xóa bài viết",
            Content: "Vui lòng chọn bài viết cần xóa."
        });
    }

}